package com.pr.makfilm.security.service.impl;

import com.pr.makfilm.domain.User;
import com.pr.makfilm.security.service.ISecurityService;
import com.pr.makfilm.service.IUserService;
import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service(SecurityServiceImpl.BEAN_NAME)
public class SecurityServiceImpl implements ISecurityService
{
   public static final String BEAN_NAME = "securityService";

   public static final Logger LOG = Logger.getLogger(SecurityServiceImpl.class);

   @Resource
   private IUserService userService;

   @Override
   public User getLoggedInUser()
   {

      SecurityContext ctx = SecurityContextHolder.getContext();
      Authentication authentication = ctx.getAuthentication();
      if (authentication == null)
      {
         return null;
      }
      Object principal = authentication.getPrincipal();
      String login = ((org.springframework.security.core.userdetails.User) principal).getUsername();
      LOG.debug("Getting logged user: " + login);
      return userService.getByLogin(login);
   }

   @Override
   public boolean hasRole(String... roles)
   {
      LOG.debug("Checking roles: " + roles.toString());
      if (roles != null)
      {
         for (String role : roles)
         {
            if (getLoggedInUser().getType().toString().equals(role))
            {
               return true;
            }
         }
      }
      return false;
   }
}
